package com.tao.dao.manager.impl;

import java.io.Serializable;
import java.util.List;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import org.hibernate.Query;
import org.hibernate.Session;

import com.tao.dao.SupeDao;
import com.tao.dao.manager.BaseDao;

public class BaseDaoImpl<T> extends SupeDao implements BaseDao<T> {

	protected Session session;
	private Class<T> clazz;

	@SuppressWarnings("unchecked")
	public BaseDaoImpl() {

		Type genericSuperclass = getClass().getGenericSuperclass();
		if (genericSuperclass instanceof ParameterizedType) {

			ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;

			Type[] actualTypeArguments = parameterizedType
					.getActualTypeArguments();
			this.clazz = (Class<T>) actualTypeArguments[0];
		} else {
			this.clazz = (Class<T>) genericSuperclass;
		}
	}

	public Class<T> getCls() {
		return clazz;
	}


	public Session getSession() {
		session =sessionFactory.openSession();
		return session;
	}


	public void closeSession() {
		if(null!=session){
		session.close();
		}
	}


	public void add(T t) {
		this.getSession().save(t);
		closeSession();
	}


	public void delete(Serializable id) {
		this.getSession().delete(this.load(id));
		closeSession();
	}


	public void update(T t) {
		this.getSession().update(t);
		closeSession();
	}


	@SuppressWarnings("unchecked")
	public T load(Serializable id) {
		T t= (T)this.getSession().get(getCls(), id);
		closeSession();
		return t;
	}


	@SuppressWarnings("unchecked")
	public List<T> list(String hql, Object[] args) {
		
		Query q = this.getSession().createQuery(hql);
		if (args != null) {
			for (int i = 0; i < args.length; i++) {
				q.setParameter(i, args[i]);
			}
		}
		List<T> list = q.list();
		closeSession();
		return list; 
	}

	public void flush() {
		if(null!=session);
		session.flush();
	}


	@SuppressWarnings("unchecked")
	public List<T> queryForPage(int offset, int length, String hql) {
		Query q = this.getSession().createQuery(hql);
		q.setFirstResult(offset); 
		q.setMaxResults(length); 
		List<T> list  = q.list();
		closeSession();
		return list; 
	}


	public int getAllRowCount(String hql, Object[] args) {
		int n= list(hql, args).size();
		closeSession();
		return n;
	}

	@Override
	public List<T> queryBySql(String sql) {
		@SuppressWarnings("unchecked")
		List<T> list = getSession().createSQLQuery(sql).list();  
		closeSession();
		return list;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public List queryAll(String sql) {
		List list = getSession().createSQLQuery(sql).list();
		closeSession();
		return list;
	}

	


}
